import React, { useEffect, useState } from "react";
import { Button, Col, Row, Space, Table, Drawer } from "antd";
import type { ColumnsType } from "antd/es/table";
import { roleBatchDel, userGet } from "@/api/user";
import { RoleType } from "@/types/user";
import UserForm from "./components/user-form";

const columns: ColumnsType<RoleType> = [
  {
    title: "用户ID",
    dataIndex: "objectId",
    key: "objectId",
    render: (id) => <a>{id}</a>,
  },
  {
    title: "账号名称",
    dataIndex: "username",
    key: "username",
  },
  {
    title: "账号ID",
    dataIndex: "roleId",
    key: "roleId",
    render: (roleId) => {
      return <>{roleId}</>;
    },
  },
  {
    title: "操作",
    key: "action",
    render: (_, record) => (
      <Space size="middle">
        <Button type="primary" size="small">
          编辑
        </Button>
        <Button type="primary" size="small" danger>
          删除
        </Button>
      </Space>
    ),
  },
];

const UserList: React.FC = () => {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<Array<RoleType>>([]);
  const [selectedIds, setSelectedIds] = useState<React.Key[]>([]);
  useEffect(() => {
    userGet().then((res) => {
      setData(res.data.results);
    });
  }, []);
  const onClose = () => {
    setOpen(false);
  };

  //配置表格可选
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`);
      setSelectedIds(selectedRowKeys);
    },
  };
  const handleBatchDel = () => {
    roleBatchDel(selectedIds).then(() => {
      let newData = data.filter((item) => !selectedIds.includes(item.objectId));
      setData(newData);
    });
  };

  return (
    <>
      <Row>
        <Col>
          <Button
            type="primary"
            onClick={() => {
              setOpen(true);
            }}
          >
            新增账号
          </Button>
          {selectedIds.length ? (
            <Button type="primary" danger onClick={handleBatchDel}>
              批量删除
            </Button>
          ) : (
            ""
          )}
        </Col>
      </Row>
      <Drawer
        title="Basic Drawer"
        placement="right"
        onClose={onClose}
        open={open}
      >
        <UserForm />
      </Drawer>
      <Table
        rowSelection={{
          type: "checkbox",
          ...rowSelection,
        }}
        columns={columns}
        dataSource={data}
        rowKey="objectId"
      />
    </>
  );
};

export default UserList;
